package io.gitee.horizon007.webspider.transformer;

import io.gitee.horizon007.webspider.WebSpider;
import io.gitee.horizon007.webspider.annotation.Context;
import io.gitee.horizon007.webspider.metadata.PropertyMetadata;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;

@Data
public class HtmlTextTransformer implements ValueTransformer {

    private final boolean html;

    @Override
    public Object transform(WebSpider webSpider, Elements elements, Object instance, PropertyMetadata propertyMetadata, Context annotation) throws Exception {

        if (propertyMetadata.isArray() || propertyMetadata.isList()) {

            if (CollectionUtils.isEmpty(elements)) {
                return propertyMetadata.isArray() ? new String[0] : Collections.emptyList();
            }

            List<? extends Class<?>> genericParameterList = propertyMetadata.getGenericParameterList();
            if (CollectionUtils.isNotEmpty(genericParameterList) && genericParameterList.get(0) == String.class) {
                Stream<String> stream = elements.stream().map(html ? Element::html : Element::text);
                return propertyMetadata.isArray() ? stream.toArray() : stream.toList();
            }

        } else if (propertyMetadata.getClassType() == String.class) {
            return CollectionUtils.isNotEmpty(elements) ? (html ? elements.get(0).html() : elements.get(0).text()) : null;
        }

        throw new Exception(String.format(
                "When using %s, only data type List<String>/String[]/String is supported, and the error is: '%s#%s'",
                getClass().getSimpleName(),
                propertyMetadata.getOwner().getType().getName(),
                propertyMetadata.getName()
        ));
    }
}
